import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { LocationService } from '../utils/location';
import { validateOfflineTiles } from '../utils/filesystem';

// 默认地图中心点（中国中心）
const DEFAULT_CENTER: MapTypes.Coordinate = {
  lng: 116.404,
  lat: 39.915
};

// 定义地图状态管理Store
export const useMapStore = defineStore('map', () => {
  // 状态
  const center = ref<MapTypes.Coordinate>(DEFAULT_CENTER);
  const zoom = ref<number>(14);
  const showLocation = ref<boolean>(true);
  const isOffline = ref<boolean>(true);
  const isTracking = ref<boolean>(false);
  const isMapLoaded = ref<boolean>(false);
  const locationError = ref<MapTypes.LocationError | null>(null);
  const tilesValidated = ref<boolean>(false);
  
  // 位置服务实例
  const locationService = new LocationService();
  
  // 计算属性
  const mapState = computed<MapTypes.MapState>(() => ({
    center: center.value,
    zoom: zoom.value,
    showLocation: showLocation.value,
    scale: 18,
    lastUpdate: new Date(),
    isOffline: isOffline.value
  }));
  
  // 方法
  
  /**
   * 更新地图中心点
   * @param newCenter 新的中心点坐标
   */
  function updateCenter(newCenter: MapTypes.Coordinate) {
    center.value = newCenter;
  }
  
  /**
   * 更新缩放级别
   * @param newZoom 新的缩放级别
   */
  function updateZoom(newZoom: number) {
    zoom.value = newZoom;
  }
  
  /**
   * 开始位置跟踪
   */
  function startTracking() {
    locationService.startLocationTracking(
      // 位置更新回调
      (position) => {
        center.value = position;
        locationError.value = null;
      },
      // 错误回调
      (error) => {
        locationError.value = error;
      }
    );
    
    isTracking.value = true;
  }
  
  /**
   * 停止位置跟踪
   */
  function stopTracking() {
    locationService.stopLocationTracking();
    isTracking.value = false;
  }
  
  /**
   * 切换位置跟踪状态
   */
  function toggleTracking() {
    if (isTracking.value) {
      stopTracking();
    } else {
      startTracking();
    }
  }
  
  /**
   * 获取当前位置并居中地图
   */
  async function centerToCurrentPosition() {
    try {
      const position = await locationService.getCurrentPosition();
      center.value = position;
      return position;
    } catch (error) {
      console.error('获取当前位置失败:', error);
      // 如果获取失败，尝试使用最后已知位置
      const lastPosition = locationService.getLastKnownPosition();
      if (lastPosition) {
        center.value = lastPosition;
        return lastPosition;
      }
      throw error;
    }
  }
  
  /**
   * 切换离线/在线模式
   */
  function toggleOfflineMode() {
    isOffline.value = !isOffline.value;
  }
  
  /**
   * 验证离线瓦片是否有效
   */
  async function validateTiles() {
    const valid = await validateOfflineTiles();
    tilesValidated.value = valid;
    return valid;
  }
  
  /**
   * 设置地图加载完成状态
   * @param loaded 是否加载完成
   */
  function setMapLoaded(loaded: boolean) {
    isMapLoaded.value = loaded;
  }
  
  /**
   * 清空错误状态
   */
  function clearError() {
    locationError.value = null;
  }
  
  return {
    // 状态
    center,
    zoom,
    showLocation,
    isOffline,
    isTracking,
    isMapLoaded,
    locationError,
    tilesValidated,
    mapState,
    
    // 方法
    updateCenter,
    updateZoom,
    startTracking,
    stopTracking,
    toggleTracking,
    centerToCurrentPosition,
    toggleOfflineMode,
    validateTiles,
    setMapLoaded,
    clearError
  };
}); 